package com.horoscope.astrology.zodiac.signs.free.fragment

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.horoscope.astrology.zodiac.signs.free.AppSettingManager
import com.horoscope.astrology.zodiac.signs.free.R
import com.horoscope.astrology.zodiac.signs.free.activity.*
import com.horoscope.astrology.zodiac.signs.free.bean.DataResultBean
import com.horoscope.astrology.zodiac.signs.free.bean.HoroscopeDataBean
import com.horoscope.astrology.zodiac.signs.free.bean.QuoteBean
import com.horoscope.astrology.zodiac.signs.free.bean.UserBean
import com.horoscope.astrology.zodiac.signs.free.network.NetworkEngine
import com.horoscope.astrology.zodiac.signs.free.network.NetworkListener
import com.horoscope.astrology.zodiac.signs.free.utils.*
import com.horoscope.astrology.zodiac.signs.free.utils.ad.ADConfig
import com.horoscope.astrology.zodiac.signs.free.utils.ad.NativeAdUtil
import com.horoscope.astrology.zodiac.signs.free.utils.ad.ad_business.ADNativeManager
import kotlinx.android.synthetic.main.ad_layout.*
import kotlinx.android.synthetic.main.fragment_horoscope.*
import kotlinx.android.synthetic.main.fragment_horoscope_new.img_ball
import kotlinx.android.synthetic.main.fragment_horoscope_new.img_bg1
import kotlinx.android.synthetic.main.fragment_horoscope_new.img_bg2
import kotlinx.android.synthetic.main.fragment_horoscope_new.img_cook
import kotlinx.android.synthetic.main.fragment_horoscope_new.iv_title_icon
import kotlinx.android.synthetic.main.fragment_horoscope_new.rating_bar
import kotlinx.android.synthetic.main.fragment_horoscope_new.rating_bar1
import kotlinx.android.synthetic.main.fragment_horoscope_new.rating_bar2
import kotlinx.android.synthetic.main.fragment_horoscope_new.rating_bar3
import kotlinx.android.synthetic.main.fragment_horoscope_new.rating_bar4
import kotlinx.android.synthetic.main.fragment_horoscope_new.tv_number
import kotlinx.android.synthetic.main.fragment_horoscope_new.tv_pisces
import kotlinx.android.synthetic.main.item_loading.*


/**
 * 星座运势
 * */
class HoroscopeFragment : BaseFragment() {

    private var mBean = UserBean()
    private var horoscope: String = ""

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_horoscope, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
    }

    private fun initView() {
        mBean = AppSettingManager.readObject("user_info") ?: return
        updateUserBean()
        horoscope = mBean.constellationName
        tv_name.text = mBean.constellationName ?: "Pisces"
        tv_pisces.text = ConstellationUtil.getDateByName(mBean.constellationName)
        iv_title_icon.setImageResource(ConstellationUtil.getIconByName(mBean.constellationName))

        view_character.setOnClickListener {
            FlurryEventUtil.putDataToEvent(EventType.TYPE_HOROSCOPE_CLICK, "type", "Character")
            val intent = Intent(activity, CharacterActivity::class.java)
            intent.putExtra("horoscope", mBean.constellationName)
            startActivity(intent)
        }

        img_quote.setOnClickListener {
            FlurryEventUtil.putDataToEvent(EventType.TYPE_HOROSCOPE_CLICK, "type", "Quote")
            val intent = Intent(activity, QuoteActivity::class.java)
            intent.putExtra("isNotification", true)
            startActivity(intent)
        }

        iv_title_icon.setOnClickListener {
            FlurryEventUtil.putDataToEvent(EventType.TYPE_HOROSCOPE_CLICK, "type", "Setting")
            startActivity(Intent(activity, SettingActivity::class.java))
        }

        img_bg1.setOnClickListener {
            FlurryEventUtil.putDataToEvent(EventType.TYPE_HOROSCOPE_CLICK, "type", "Horoscope")
            startActivity(Intent(activity, HoroscopeActivity::class.java))
        }
        img_bg2.setOnClickListener {
            FlurryEventUtil.putDataToEvent(EventType.TYPE_HOROSCOPE_CLICK, "type", "Daily_Number")
            startActivity(Intent(activity, FourNumberActivity::class.java))
        }

        img_ball.setOnClickListener {
            FlurryEventUtil.putDataToEvent(EventType.TYPE_HOROSCOPE_CLICK, "type", "Magic_Ball")
            startActivity(Intent(activity, MagicBallActivity::class.java))
        }

        img_cook.setOnClickListener {
            FlurryEventUtil.putDataToEvent(EventType.TYPE_HOROSCOPE_CLICK, "type", "Fortune_Cookie")
            startActivity(Intent(activity, FortuneActivity::class.java))
        }

        // 先判断是否当天首次登陆 && 是否有储存相应数据
        if (AppSettingManager.contains("HoroscopeData") && !SysUtils.isTodayFirstLogin(
                mBean.constellationName,
                "HoroscopeDate"
            )
        ) {
            showLoaded(loading, loading_out)
            val str = AppSettingManager.readString("HoroscopeData", "")
            val map: Map<String, DataResultBean> =
                Gson().fromJson(str, object : TypeToken<Map<String, DataResultBean>>() {}.type)
            val t = map[mBean.constellationName]
            t?.let {
                setRate(
                    t.data.daily_number.toFloat(),
                    t.data.today[0].rate.toFloat(),
                    t.data.today[1].rate.toFloat(),
                    t.data.today[2].rate.toFloat(),
                    t.data.today[3].rate.toFloat()
                )
                tv_number.text = t.data.daily_number.toString()
            }
            try {
                isShowNativeAd()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        } else {
            loadData()
        }
    }

    // 星座日期更改，线上用户数据更新
    private fun updateUserBean() {
        if (AppSettingManager.readInt("update_bean", 0) == 0) {
            val birthDay = mBean.birthday
            val month = birthDay.split("-")[0].toInt()
            val day = birthDay.split("-")[1].toInt()
            mBean.constellationName = ConstellationUtil.getConstellationName(month - 1, day)
            AppSettingManager.saveObject(mBean, "user_info")
            AppSettingManager.saveInt(1, "update_bean")
        }
    }

    private fun isShowNativeAd() {
        val nativeAdBean = ADNativeManager.mInstance.getNativeAdBean("Native_Home")
        if (nativeAdBean != null) {
            include_ad.visibility = View.VISIBLE
            // 通过advertiser判断显示那个原生广告视图
            when (nativeAdBean.adInfo.advertiser) {
                ADConfig.FB -> {
                    native_ad_container.visibility = View.VISIBLE
                    ad_frame.visibility = View.GONE
                    if (nativeAdBean.facebookNativeAD != null) {
                        NativeAdUtil.inflateFacebookAd(
                            nativeAdBean.facebookNativeAD,
                            include_ad, "Horoscope_Small", "Native_Home"
                        )
                        include_ad.visibility = View.VISIBLE
                    } else {
                        include_ad.visibility = View.GONE
                    }
                }
                ADConfig.ADMOB -> {
                    ad_frame.visibility = View.VISIBLE
                    native_ad_container.visibility = View.GONE
                    if (nativeAdBean.googleNativeAd != null) {
                        NativeAdUtil.inflateAdMobAd(
                            nativeAdBean.googleNativeAd!!,
                            include_ad,
                            "Horoscope_Small"
                        )
                        include_ad.visibility = View.VISIBLE
                    } else {
                        include_ad.visibility = View.GONE
                    }
                }
            }
        } else {
            include_ad.visibility = View.GONE
        }
    }


    // 双击刷新数据
    fun loadData() {
        try {
            isShowNativeAd()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        if (loading != null && loading_out != null) {
            showLoading(loading, loading_out)
        } else {
            include_loading.visibility = View.INVISIBLE
        }
        NetworkEngine.getHoroscopeData(mBean.constellationName, listenerMain)
    }

    private fun refreshQuote() {
        // 初始化 和 数据使用完毕都显示第一条
        if (AppSettingManager.contains("quote_bean")) {
            val content =
                AppSettingManager.readQuote("quote_bean")!!.text.ifEmpty { getString(R.string.text_daily_quote_sub_text) }
            val author =
                StringBuilder("-" + AppSettingManager.readQuote("quote_bean")!!.author.ifEmpty {
                    getString(R.string.text_daily_quote_author)
                })
            tv_daily_quote_sub_text.text = content
            tv_daily_quote_author.text = author
        } else {
            AppSettingManager.saveObject(
                QuoteBean(
                    getString(R.string.text_daily_quote_sub_text),
                    getString(R.string.text_daily_quote_author),
                    1, "", ""
                ),
                "quote_bean"
            )
        }
    }

    private val listenerMain = object : NetworkListener<HoroscopeDataBean>() {
        override fun onSuccess(t: HoroscopeDataBean) {
            if (isAdded && t.data.today.size > 0) {
                showLoaded(loading, loading_out)

                val map = mapOf(Pair(mBean.constellationName, t))
                val str = Gson().toJson(map)

                AppSettingManager.saveString(str, "HoroscopeData")

                setRate(
                    t.data.daily_number.toFloat(),
                    t.data.today[0].rate.toFloat(),
                    t.data.today[1].rate.toFloat(),
                    t.data.today[2].rate.toFloat(),
                    t.data.today[3].rate.toFloat()
                )

                tv_number.text = t.data.daily_number.toString()

                AppSettingManager.saveString(SysUtils.getStringDate(), "HoroscopeDate")
            } else {
                showLoaded(loading, loading_out)
            }

        }

        override fun onFailed(t: HoroscopeDataBean) {
            super.onFailed(t)
            showLoaded(loading, loading_out)
            if (isAdded && !isHidden) {
                ToastUtil.showRewardError(activity)
            }
        }

        override fun onError(e: String?) {
            super.onError(e)
            showLoaded(loading, loading_out)
            if (isAdded && !isHidden) {
                ToastUtil.showRewardError(activity)
            }
        }
    }

    // 设置所有的RatingBar
    private fun setRate(float: Float, float0: Float, float1: Float, float2: Float, float3: Float) {
        rating_bar.rating = float
        rating_bar1.rating = float0
        rating_bar2.rating = float2
        rating_bar3.rating = float1
        rating_bar4.rating = float3
    }

    override fun onStart() {
        super.onStart()
        checkConstellation()
        refreshQuote()
        // 不在浏览状态
        AppSettingManager.saveInt(0, "Quote_Now")
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            checkConstellation()
        }
    }

    // 及时改变星座图 onResume()
    private fun checkConstellation() {
        mBean = AppSettingManager.readObject("user_info") ?: return
        if (mBean.constellationName.isNotEmpty() && horoscope != mBean.constellationName) {
            tv_name.text = mBean.constellationName ?: "Pisces"
            iv_title_icon.setImageResource(ConstellationUtil.getIconByName(mBean.constellationName))
            tv_pisces.text = ConstellationUtil.getDateByName(mBean.constellationName)
            loadData()
        }
    }

}